package com.minjie.controller;

import com.minjie.pojo.Result;
import com.minjie.pojo.User;
import com.minjie.service.UserService;
import com.minjie.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //添加用户功能
    @PostMapping("/add")
    public String addUser(@RequestBody User user) {
        userService.addUser(user);
        return "用户添加成功";
    }

    //用户登录功能
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        log.info("用户登录"+user);
        User u = userService.login(user);
        //登录成功，生成令牌，下发令牌
        if (u!=null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("name",u.getName());
            claims.put("username",u.getUsername());
            //生成JWT令牌
            String token = JwtUtils.generateJwt(claims);
            return Result.success(token);
        }
        //登录失败，返回错误信息
        return Result.error("用户名或密码错误");
    }

    //根据已登录用户 token 获取用户名，根据用户名返回用户信息
    //有token则返回成功信息，没有则返回失败信息
    @GetMapping("/info")
    public Result userInfo(@RequestHeader("Authorization") String token) {
        try {
            User userInfo = userService.getUserInfoByToken(token);
            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error("用户名或密码错误");
        }
    }
}
